package tools

import (
	"encoding/json"
	"fmt"
	"os/exec"

	"workflow-gui/internal/protocol"
)

// GUIHandler handles GUI-related tool requests
type GUIHandler struct {
	projectRoot string
}

// NewGUIHandler creates a new GUI handler
func NewGUIHandler(projectRoot string) *GUIHandler {
	return &GUIHandler{
		projectRoot: projectRoot,
	}
}

// HandleOpenGUI handles the open_gui tool request
func (h *GUIHandler) HandleOpenGUI(args map[string]interface{}) (protocol.ToolResult, error) {
	// Use WPF main window via HTTP request to GUI service
	// This ensures the GUI service is running and manages the window lifecycle
	
	// Make HTTP request to GUI service
	cmd := exec.Command("curl", "-X", "POST", "http://localhost:9081/gui/main")
	output, err := cmd.CombinedOutput()
	
	if err != nil {
		return protocol.NewErrorResult(fmt.Sprintf("Failed to open GUI: %v\nOutput: %s", err, string(output))), nil
	}

	// Parse response
	var response map[string]interface{}
	if err := json.Unmarshal(output, &response); err != nil {
		return protocol.NewErrorResult(fmt.Sprintf("Failed to parse response: %v", err)), nil
	}

	// Check for error in response
	if errMsg, ok := response["error"].(string); ok {
		return protocol.NewErrorResult(fmt.Sprintf("GUI service error: %s", errMsg)), nil
	}

	// Return success
	result := map[string]interface{}{
		"success": true,
		"message": "Workflow Manager GUI (WPF) 已打开",
	}

	resultJSON, err := json.Marshal(result)
	if err != nil {
		return protocol.NewErrorResult(fmt.Sprintf("Failed to serialize result: %v", err)), nil
	}

	return protocol.NewSuccessResult(string(resultJSON)), nil
}
